<template>
  <div class="music-player">
    <audio
      ref="audioElement"
      :src="playUrl"
      @ended="handleEnded"
    ></audio>
    <!-- controls -->
    <!-- <div class="player-controls">
      <audio autoplay id="myAudio">
        <source src="@/assets/bgmusic.mp3" type="audio/mpeg" />
      </audio>
      背景音乐：<button id="playPauseButton">播放/暂停</button>
    </div> -->
    <div class="player-controls">
      背景音乐<button @click="playPause">
        {{ isPlaying ? "Pause" : "Play" }}
      </button>
    </div>
  </div>
</template>

<script lang="ts">
import { ref, onMounted, watch } from "vue";
import { Howl } from "howler";

export default {
  name: "MusicPlayer",
  props: {
    data: {
      type: Object,
      required: true,
    },
  },
  setup(props) {
    const isPlaying = ref(false);
    const playUrl = ref(props.data.playurl);
    // const playUrl = ref("@/assets/bgmusic.mp3");
    // const audioElement = ref<HTMLAudioElement | null>(null);

    const sound = new Howl({
      src: [playUrl.value],
      // autoplay: true,
      // loop: true,
      // volume: 0.5,
      onend: () => {
        isPlaying.value = false;
        handleEnded();
      },
    });

    const playPause = () => {
      if (isPlaying.value) {
        sound.pause();
      } else {
        sound.play();
      }
      isPlaying.value = !isPlaying.value;
    };

    const handleEnded = () => {
      // 处理播放结束的逻辑，例如更新播放次数等
    };

    onMounted(() => {
      sound.load();
      // 获取音频元素和控制按钮
      let myAudio = document.getElementById("myAudio") as HTMLAudioElement;
      let playPauseButton = document.getElementById(
        "playPauseButton"
      ) as HTMLButtonElement;
      setTimeout(() => {
        playPause();
        // 添加播放/暂停按钮的点击事件
        playPauseButton &&
          playPauseButton.addEventListener("click", function () {
            if (myAudio.paused) {
              myAudio && myAudio.play();
              playPauseButton.innerHTML = "暂停";
            } else {
              myAudio && myAudio.pause();
              playPauseButton.innerHTML = "播放";
            }
          });
      }, 3000);
    });

    watch(playUrl, (newVal: string, oldVal) => {
      if (newVal !== oldVal) {
        sound.unload();
        sound.load();
      }
    });

    return {
      isPlaying,
      playUrl,
      // audioElement,
      playPause,
      handleEnded,
    };
  },
};
</script>

<style scoped>
.music-player {
  width: 300px;
  /* 样式根据需求自定义 */
}

.player-controls {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 10px;
}
</style>
